package com.record.utils;



import org.apache.commons.math3.distribution.ChiSquaredDistribution;
import java.util.*;

public class KruskalWallisCalculator {

    /**
     * Kruskal–Wallis H 检验（非参数检验，适用于多独立样本）
     */
    public static KruskalWallisResult test(double[][] groups) {
        int k = groups.length;
        int totalN = Arrays.stream(groups).mapToInt(g -> g.length).sum();

        // 合并数据
        List<Double> allValues = new ArrayList<>();
        for (double[] g : groups) {
            for (double v : g) allValues.add(v);
        }

        // 排序并分配秩
        List<Double> sorted = new ArrayList<>(allValues);
        Collections.sort(sorted);
        Map<Double, Double> rankMap = new HashMap<>();
        for (int i = 0; i < sorted.size(); i++) {
            rankMap.put(sorted.get(i), (double) (i + 1));
        }

        // 计算每组秩和
        double[] rankSum = new double[k];
        for (int i = 0; i < k; i++) {
            for (double v : groups[i]) {
                rankSum[i] += rankMap.get(v);
            }
        }

        // 计算H值
        double H = 0.0;
        for (int i = 0; i < k; i++) {
            H += Math.pow(rankSum[i], 2) / groups[i].length;
        }
        H = (12.0 / (totalN * (totalN + 1)) * H) - 3 * (totalN + 1);

        // 计算p值（卡方近似）
        ChiSquaredDistribution chi = new ChiSquaredDistribution(k - 1);
        double pValue = 1 - chi.cumulativeProbability(H);

        return new KruskalWallisResult(H, pValue);
    }
}
